﻿// ASP.NET Web API Sample Application
// by Lee Dumond -- leedumond@gmail.com

namespace ContactManagerCrud.Controllers
{
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Net;
   using System.Net.Http;
   using System.Web.Http;
   using Models;

   public class ContactsController : ApiController
   {
      private static readonly IContactRepository repository = new ContactRepository();

      public IEnumerable<Contact> GetContacts()
      {
         return repository.GetAll();
      }

      public Contact GetContactById(int id)
      {
         Contact contact = repository.Get(id);

         if (contact == null)
         {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
         }

         return contact;
      }

      public IEnumerable<Contact> GetContactsByEmailDomain(string domain)
      {
         return repository.GetAll().Where(c => c.Email.Contains("@" + domain));
      }

      public HttpResponseMessage PostContact(Contact contact)
      {
         if (!ModelState.IsValid)
         {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
         }

         Contact newContact = repository.Add(contact);

         HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, newContact);

         string url = Url.Link("DefaultApi", new {id = contact.Id});
         response.Headers.Location = new Uri(url);

         return response;
      }

      public void PutContact(Contact contact)
      {
         if (!ModelState.IsValid)
         {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
         }

         if (!repository.Update(contact))
         {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
         }
      }

      public HttpResponseMessage DeleteContact(int id)
      {
         repository.Remove(id);
         return new HttpResponseMessage(HttpStatusCode.NoContent);
      }

      public IEnumerable<Contact> GetContactsByName(string name)
      {
         throw new NotImplementedException();
      }
   }
}